package com.singzi.javaSenior.threads.threadPool.forkJoin.example1;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        SumTask sumTask = new SumTask(1,100000000);
        ForkJoinTask<Long> submit = forkJoinPool.submit(sumTask);
        do {
            System.out.printf("Main: Thread Count: %d\n",forkJoinPool.getActiveThreadCount());
            System.out.printf("Main: Paralelism: %d\n",forkJoinPool.getParallelism());
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (!sumTask.isDone());

        //输出结果
        System.out.println(submit.get());


    }
}
class SumTask extends RecursiveTask<Long> {
    private int start;
    private int end;

    public SumTask(int start, int end) {
        this.start = start;
        this.end = end;
    }
    public static final int threshold = 5;


    @Override
    protected Long compute() {
        long sum = 0;
        boolean canCompute = (end - start) <= threshold;
        if(canCompute){
            for(int i = start;i <= end;i++){
                sum += i;
            }
        }else{
            int mid = start + (end - start)/2;
            SumTask sumTask1 = new SumTask(start, mid);
            SumTask sumTask2 = new SumTask(mid+1, end);
            invokeAll(sumTask1, sumTask2);
            Long sum1 = sumTask1.join();
            Long sum2 = sumTask2.join();
            sum = sum1 + sum2;
        }
        return sum;
    }
}